import {userAction} from 'WE/Action';
import {userStore} from 'WE/Stores';
import {buildSign} from 'WE/Utils';
import {globalService} from 'M/Services';
import ErrorCodes from 'WE/ErrorCodes';
class UserService {
  async login({captcha, phone, name}) {
    const {publicKey} = await userStore.getKeyStringOrInit();
    const appKey = captcha;
    const {sign, ...data} = await userAction.login({
      sign: buildSign({data: {publicKey, phone, name}, appKey}),
      publicKey,
      phone,
      name,
    });
    globalService.throwError(
      sign !== buildSign({data, appKey}),
      ErrorCodes.InvalidData,
    );
    await userStore.saveUserData({...data, name});
    this.events.forEach(event =>
      event({
        isLogin: true,
        phone,
        name,
        appKey,
        serverPublicKey: data.publicKey,
      }),
    );
  }

  async sendCaptchaSms({phone}) {
    const data = await userAction.sendCaptchaSms({phone});
    const {maskNames = [], registered, ...other} = data;
    return {
      maskNames,
      showUserName: true, // 先不管是否新用户都需要输入用户名。
      showMaskName: maskNames.length > 0,
      ...other,
    };
  }

  getSyncName() {
    return userStore.getSyncName();
  }

  getName() {
    return userStore.getName();
  }
  events = [];

  async logout() {
    await userStore.logout();
    this.events.forEach(event => event({isLogin: false}));
  }
  addListener(event) {
    this.events.push(event);
  }
}

export default new UserService();
